#include <iostream>
#include <vector>
#include <list>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>

#include "GeomSvc.h"
#include "TriggerRoad.h"

using namespace std;

int main(int argc, char* argv[])
{
  GeomSvc* p_geomSvc = GeomSvc::instance();
  p_geomSvc->init("geometry_R962");

  Double_t mass, xF, x1, x2;
  Double_t weight;
  Double_t x0, y0, z0;

  Double_t px1, py1, pz1, p1;
  Double_t px2, py2, pz2, p2;

  Int_t nHodoHits1;
  Int_t detectorID1[100];
  Int_t elementID1[100];

  Int_t nHodoHits2;
  Int_t detectorID2[100];
  Int_t elementID2[100];

  TFile* dataFile = new TFile(argv[1], "READ");
  TTree* dataTree = (TTree*)dataFile->Get("save");

  dataTree->SetBranchAddress("weight", &weight);
  dataTree->SetBranchAddress("z0", &z0);

  dataTree->SetBranchAddress("nHodoHits1", &nHodoHits1);
  dataTree->SetBranchAddress("detectorID1", detectorID1);
  dataTree->SetBranchAddress("elementID1", elementID1);

  dataTree->SetBranchAddress("nHodoHits2", &nHodoHits2);
  dataTree->SetBranchAddress("detectorID2", detectorID2);
  dataTree->SetBranchAddress("elementID2", elementID2);

  TriggerRoad* p_road = new TriggerRoad(); p_road->clear();
  TriggerRoad* m_road = new TriggerRoad(); m_road->clear();

  TFile* saveFile = new TFile(argv[2], "recreate");
  TTree* saveTree = dataTree->CloneTree(0);

  saveTree->Branch("p_road", &p_road, 256000, 99);
  saveTree->Branch("m_road", &m_road, 256000, 99);

  for(int i = 0; i < dataTree->GetEntries(); i++)
    {
      dataTree->GetEntry(i);

      for(int j = 0; j < nHodoHits1; j++)
	{
	  if(p_geomSvc->getDetectorName(detectorID1[j]).find("X") == std::string::npos) continue;
	  m_road->addElement(detectorID1[j], elementID1[j]);
	}

      for(int j = 0; j < nHodoHits2; j++)
	{
	  if(p_geomSvc->getDetectorName(detectorID2[j]).find("X") == std::string::npos) continue;
	  p_road->addElement(detectorID2[j], elementID2[j]);
	}

      if(z0 > 0)
	{
	  m_road->dumpWeight += weight;
	  p_road->dumpWeight += weight;
	}
      else
	{
	  m_road->targetWeight += weight;
	  p_road->targetWeight += weight;
	}

      if(p_road->getNElements() == 4 && m_road->getNElements() == 4) saveTree->Fill();
      p_road->clear();
      m_road->clear();
    }

  saveFile->cd();
  saveTree->Write();
  saveFile->Close();

  return 1;
}
